import logging
import os
from time import sleep

import requests
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver

from config import driver_path, chrome_options
from utils.cartoon_util import download_cartoon_by_executor
from utils.thread_util import FutureManagement

browser: WebDriver


def get_chapterlist(chapterlist_url: str):
    text = requests.get(chapterlist_url).text
    list = eval(text).get('data').get('list')

    return list


def get_img_url_list(chapter_url: str):
    browser.get(chapter_url)
    # 获取图片元素
    image_elements = browser.find_elements_by_css_selector("img")
    return [image_element.get_attribute("data-src") for image_element in image_elements if
            image_element.get_attribute("data-src") is not None]


def download_chapter(name, chapter_url):
    img_url_list = get_img_url_list(chapter_url)

    name, future = download_cartoon_by_executor(name, img_url_list)

    return name, future


def download(parameter: str):
    home = 'http://www.kumw7.com/{}/'.format(parameter)
    chapterlist_url = 'http://www.kumw7.com/chapterlist/{}/'.format(parameter)

    chapterlist = get_chapterlist(chapterlist_url)

    global browser
    browser = webdriver.Chrome(executable_path=driver_path, options=chrome_options)
    future_management = FutureManagement()

    for chapter in chapterlist:
        id, name = chapter.values()
        chapter_url = '{}/{}.html'.format(home, id)
        name, future = download_chapter(name, chapter_url)
        future_management.add_a_future(name, future)
        logging.info('future size:{}'.format(future_management.size()))
        sleep(10)

        for name in future_management.patrol():
            logging.info(name + ' 下载完成')

    browser.quit()

    while future_management.exist_future():
        logging.info('future size:{}'.format(future_management.size()))
        sleep(10)
        for name in future_management.patrol():
            logging.info(name + ' 下载完成')


if __name__ == '__main__':
    download('21429')  # 参数为漫画id
